/* 
 * socketConn.h
 *
 *  Created on: 11/02/2014
 *      Author: Emiliano R. Gudino
 */

#ifndef SOCKETCONN_H_
#define SOCKETCONN_H_

#include <sys/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <stdlib.h>

#include <semaphore.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include "scpi/scpi.h"
#include "scpi/commands.h"
#include "scpi/responses.h"
#include "scpi/scpi_includes/scpi_def.h"

#define TYPE_SCPI_CMD 	'S'
#define TYPE_PARSED_CMD 'R'
#define DATA_OK		1
#define DATA_PENDING	0

// File names of the different sockets
#define FASTCGI_SOCKET_FILENAME "/tmp/fastcgi_socket"
#define TCP_SOCKET_FILENAME     "/tmp/tcp_socket"
#define TELNET_SOCKET_FILENAME  "/tmp/telnet_socket"
#define SERIAL_SOCKET_FILENAME  "/tmp/serial_socket"
#define LOCAL_SOCKET_TOTAL	4

#define MAX_PARAM_LENGTH	256

using namespace std;

typedef struct Command_Request
{
	char command_id;														// The parsed command
	char command_suffix;													// The parsed command suffix
	char argument_count;													// number of parsed arguments
	char arguments[MAX_PARAM_LENGTH];										// The parsed arguments
} command_request_str;

typedef struct Command_Response
{
	char response_type;														// The type of response
	char response[MAX_PARAM_LENGTH];										// The response
} command_response_str;

class Socket_Conn
{
  public:
	Socket_Conn(void);														// Constructor
	  virtual ~ Socket_Conn();												// Destructor
	void Set_Socket_Server(int);											// Set the socket server ID.
	int Get_Socket_Server();												// Get the socket server ID.
	void Set_Socket_Client(int);											// Set the socket client ID.
	int Get_Socket_Client();												// Get the socket client ID.
	void Connect(sem_t *, string);											// Launch the socket listener thread
	void Disconnect(void);													// Close the socket
	bool Get_Command(command_request_str *);								// Read and clean the data in the buffer.
	void Set_Response(command_response_str *);								// Read and clean the data in the buffer.

  private:
	int socket_server, socket_client;										// Sockets identifier
	bool socket_open;
	struct sockaddr_un name;												// Socket name structure
	string socket_name;														// Socket filename
	pthread_t thread;														// Socket listener thread
	command_request_str command_request;									// Commands buffer
	command_response_str command_response;									// Responses buffer
	char cmd_processed_flag;												// Flag that show if the data was processed
	sem_t buffer_queue_count;												// Semaphore that wait the process finish
	sem_t *global_queue_count;												// Semaphore that wait for a new command
	static void *Socket_Listener(void *);
	static void Scpi_Parser(char *, Socket_Conn *);							// Interprets the scpi commands

};



#endif /* SOCKETCONN_H_ */
